<template>
  <view class="biwd">
    <SimpleControl
      hide-offline-tips-forced
      :control="(control as BaseController.Control)"
      :flex-area-links="flexAreaLinks"
      :notice-external-methods="noticeExternalMethods"
    >
      <template #aside-control>
        <AsideControl
          v-if="!isOffline && showChildLock"
          :title="$t('BIWD.ChildLock.Title.Text')"
          :desc="$t('BIWD.ChildLock.Off.Text')"
          :desc-active="$t('BIWD.ChildLock.On.Text')"
          :actived="childLockOn"
          @change="onChildLockChange"
        />
        <AsideControl
          v-if="isSelectedProgramVisible"
          :disabled="isOffline === true"
          title="控制"
          @change="jumpProgramView"
        />
      </template>
      <FilterInfoView
        :control="control"
        :circle-width="circleWidth"
        :disabled="isOffline === true"
        :is-offline="isOffline === true"
      ></FilterInfoView>
      <BuyFilterView :control="control" :brand="brand" :vib="vib" :is-offline="isOffline === true"></BuyFilterView>
      <!-- 冰水设置 -->
      <CoolWaterView v-model:show="coolWaterSetVisible" :ha-id="haId" :control="control"></CoolWaterView>
    </SimpleControl>
    <!-- 童锁提示弹框 -->
    <Modal
      v-model:visible="isShowChildTipView"
      :title="$t('BIWD.ChildLock.Dialog.Title')"
      :ok-text="$t('BIWD.ChildLock.Dialog.Confirm.Text')"
      @ok="hideChildTipView"
    >
      <view class="notify-text">{{ childTipText }}</view>
    </Modal>
    <Modal v-model:visible="errorVisible" :title="errorTitle" :header-style="headerStyle">
      <view class="error-code">（{{ $t('BIWD.ErrorTips.Dialog.ErrorCode.Label') }} {{ errorCode }}）</view>
      <view class="error-des">{{ $t('BIWD.ErrorTips.Dialog.ErrorDes.Text') }}</view>
      <view class="phone-box">
        <view class="error-phone-box">
          <view class="phone-title">{{ $t('BIWD.ErrorTips.Dialog.CallPhone.Label') }}</view>
          <view class="phone">{{ phoneNumber }}</view>
        </view>
        <view class="call-phone" @click="showServePhone">
          <text>{{ $t('BIWD.ErrorTips.Dialog.CallPhone.Button') }}</text>
          <image class="call-right-arrow" src="@/pages/appliance/static/TT/ic_error_right.png"></image>
        </view>
      </view>
    </Modal>
    <Modal
      v-model:visible="phoneVisible"
      :title="$t('BIWD.ServePhone.Dialog.Title')"
      :description="phoneNumber"
      :ok-text="$t('BIWD.ServePhone.Dialog.Ok.Button')"
      :cancel-text="$t('BIWD.ServePhone.Dialog.Cancel.Button')"
      @ok="callPhone"
    />
    <!-- 固件升级成功 -->
    <SuccessAcknowledge v-if="otaHelper" :helper="otaHelper" />
  </view>
</template>
<script setup lang="ts">
import Modal from '@/common/modal.vue'
import FilterInfoView from './filterInfoView.vue'
import BuyFilterView from './buyFilterView.vue'
import SimpleControl from '@/pages/appliance/view/control/simpleControl.vue'
import AsideControl from '../view/control/components/AsideControl.vue'
import CoolWaterView from './coolWaterView.vue'

import type { BaseController } from '@/controller/BaseAppliance/definition'
import { useScrollProvider } from '@/utils/composition/useScroll'
// 注意：请勿将onShareAppMessage删除
import { onLoad, onPageScroll, onShareAppMessage, onUnload } from '@dcloudio/uni-app'
import type { FlexAreaLink } from '../view/control/components/FlexArea.vue'
import { callEventSender, toPage } from '@/utils/mpHelper'
import { useI18n } from 'vue-i18n'
import { BIWD_WATERTREATMENT_ERRORCODE, MachineError, OperationState } from '@/constants/WDCommand'
import { ActionType, type Notice } from '@/types/notice'
import type { BIWDController } from '@/controller/BIWD/definition'
import { useControlState } from '@/controller/BaseAppliance/useControl'
import netconfig from '@/config/netconfig'
import { createOtaHelper } from '../settings/ota/helpers'
import type { OTAHelper } from '../settings/ota/helpers/types'
import { useApplianceStore } from '@/store/appliance'
import SuccessAcknowledge from '../settings/ota/modals/successAcknowledge.vue'

const i18n = useI18n()
const headerStyle = {
  paddingBottom: '8rpx',
}

const props = defineProps<{
  control: BIWDController.Control
}>()

const { setScrollTop } = useScrollProvider()
onPageScroll(({ scrollTop }) => setScrollTop(scrollTop))

const { store } = props.control

const controlState = useControlState(props.control)
const { isOffline } = controlState
const applianceStore = useApplianceStore()

const haId = computed(() => store._datasource.haId)
const vib = computed(() => store._datasource.vib)
const brand = computed(() => store._datasource.brand.toUpperCase())
const phoneNumber = computed(() => (brand.value === 'BOSCH' ? '400 885 5888' : '400 889 9999'))
const customName = computed(() =>
  brand.value === 'BOSCH' ? i18n.t('BIWD.FlexArea.MyCustom.Bosh.Label') : i18n.t('BIWD.FlexArea.MyCustom.Siemens.Label')
)

const flexAreaLinks = computed(() => {
  if (!store._datasource.loaded) return []

  const links: FlexAreaLink[] = []
  if (store.isFavorite) {
    links.push({
      icon: '/pages/appliance/static/Favorite.png',
      name: i18n.t('BIWD.FlexArea.MyFavorite.Label'),
      trackCode: 'BIWD.FlexArea.MyFavorite.Label',
      disabled: isOffline.value === true,
      onClick: jumpMyFavorite,
    })
  }
  if (store.isCustom) {
    links.push({
      icon: '/pages/appliance/static/Favorite.png',
      name: customName.value,
      trackCode: '',
      disabled: isOffline.value === true,
      onClick: () => jumpCustomFavorite(),
    })
  }

  if (store.isCoolWater) {
    links.push({
      icon: '/pages/appliance/static/Icewater.png',
      name: i18n.t('BIWD.FlexArea.CoolWaterSet.Label'),
      trackCode: '',
      disabled: isOffline.value === true,
      onClick: () => jumpCoolWater(),
    })
  }
  links.push({
    icon: '/pages/appliance/static/WaterQuality.png',
    name: i18n.t('BIWD.FlexArea.WaterInfo.Label'),
    trackCode: 'BIWD.FlexArea.WaterInfo.Label',
    disabled: isOffline.value === true,
    onClick: () => jumpWaterInfo(),
  })
  return links
})

// 创建固件升级方法
const otaHelper: OTAHelper | null = createOtaHelper({
  brand: applianceStore.current?.brand || '',
  type: applianceStore.current?.type || '',
  vib: applianceStore.current?.vib || '',
  haId: applianceStore.current?.haId || '',
  scene: 'detail',
})

/**
 * ota升级
 */
const notice: Notice = {
  key: 'BSH.Common.Event.SoftwareUpdateAvailable',
  value: 'BSH.Common.EnumType.EventPresentState.Present',
  description: '检测到家电固件版本有更新。',
  closable: true,
  color: 1,
  ranking: 0,
  brand: store._datasource.brand,
  type: store._datasource.type,
  vib: store._datasource.vib,
  triggerActionImmediate: false,
  action: {
    landingPage: 'pages/appliance/settings/ota/firmwareUpdate',
    linkText: '去升级',
    type: 3,
  },
}
watch(
  () => otaHelper?.upgradeDetected.value,
  (upgradeDetected) => {
    store.updateDetected = upgradeDetected as boolean
    if (store.updateDetected) {
      store.addNotice(notice)
    } else {
      store.removeNotice(notice)
    }
  }
)
watch(
  () => isOffline.value,
  (isOffline) => {
    if (isOffline === false) {
      otaHelper?.checkUpgrade()
    }
  }
)

onUnload(() => {
  otaHelper?.destroy()
})

/**
 * 圆环
 */
const res = uni.getSystemInfoSync()
const circleWidth = res.screenWidth / 750

/**
 * 童锁
 */
const showChildLock = computed(() =>
  ['WBB8060B2C', 'WBB8060B1C', 'WS7060BB1C', 'WS7061BB1C'].includes(store._datasource.vib)
)
const isShowChildTipView = ref(false)
const childTipText = ref('')
const childLockOn = computed(() => store.childLock === 1)
const childTipOnText = i18n.t('BIWD.ChildLock.Dialog.Content.On.Text')
const childTipOffText = i18n.t('BIWD.ChildLock.Dialog.Content.Off.Text')
watch(
  () => childLockOn.value,
  (value) => {
    if (isShowChildTipView.value) {
      if (!value) {
        childTipText.value = childTipOnText
      } else {
        childTipText.value = childTipOffText
      }
    }
  }
)
function onChildLockChange() {
  childTipText.value = childLockOn.value ? childTipOffText : childTipOnText
  isShowChildTipView.value = true
}

/**
 * 隐藏童锁提示弹框
 */
function hideChildTipView() {
  isShowChildTipView.value = false
  childTipText.value = ''
}

/**
 * 跳转我的收藏页面
 */
async function jumpMyFavorite() {
  const res = await toPage('/pages/appliance/BIWD/favoriteList/favoriteList', {
    haId: haId.value,
    isVirtual: store.isVirtualAppliance,
  })
  callEventSender(res.eventChannel, 'control', props.control)
}

/**
 * 跳转自定义程序页面
 */
async function jumpCustomFavorite() {
  const res = await toPage('/pages/appliance/BIWD/customProgram/customProgram', {
    haId: haId.value,
    brand: brand.value,
  })
  callEventSender(res.eventChannel, 'control', props.control)
}

/**
 * 跳转水质信息
 */
async function jumpWaterInfo() {
  const res = await toPage('/pages/appliance/BIWD/waterInfo/waterInfo')
  callEventSender(res.eventChannel, 'control', props.control)
}

/**
 * 跳转选择程序页面
 */
let isSelectedProgramVisible = computed(() => netconfig.isTester && !store.isVirtualAppliance)
async function jumpProgramView() {
  const res = await toPage('/pages/appliance/BIWD/programView/programView', {
    haId: haId.value,
    vib: store._datasource.vib,
  })
  callEventSender(res.eventChannel, 'control', props.control)
}

/**
 * 运行状态通知
 */
watch(
  () => [store.runState, store.cleanState],
  () => {
    handleRunStatus(store.runState)
  }
)

function handleRunStatus(value: number) {
  let notice: Notice = {
    key: OperationState,
    value,
    description: '',
    closable: true,
    color: 2,
    ranking: 1,
    brand: store._datasource.brand,
    type: store._datasource.type,
    vib: store._datasource.vib,
    action: null,
  }
  if (value === 3 && store.cleanState === 0) {
    notice.description = '出水中'
    store.addNotice(notice)
  } else {
    store.removeNotice(notice)
  }
}

/**
 * 跳转冰水设置
 */
const coolWaterSetVisible = ref(false)
function jumpCoolWater() {
  coolWaterSetVisible.value = true
}

/**
 * 监听错误码
 */
const errorVisible = ref(false)
const errorTitle = ref('')
const errorCode = ref('')
watch(
  () => store.errorCode,
  (value) => {
    handleErrorCode(value)
  }
)
watch(
  () => store.valueErrorCode,
  (value) => {
    handleValueErrorCode(value)
  }
)

function handleErrorCode(value: number) {
  let notice: Notice = {
    key: MachineError,
    value,
    description: '',
    closable: false,
    color: 2,
    ranking: 1,
    brand: store._datasource.brand,
    type: store._datasource.type,
    vib: store._datasource.vib,
    action: null,
  }
  let callPhone = false
  let generalTips = false
  let binaryData = parseInt(value + '').toString(2)
  let binaryArray = binaryData.split('')
  let allBinaryArray = new Array(32).fill(0)
  for (let i = 0; i < binaryArray.length; i++) {
    allBinaryArray[32 - binaryArray.length + i] = parseInt(binaryArray[i])
  }

  let title = ''
  let code = ''
  if (allBinaryArray[8] == 1) {
    callPhone = true
    code = 'E1'
    title = '发热膜回路故障'
  } else if (allBinaryArray[9] == 1) {
    callPhone = true
    code = 'E2'
    title = '制水异常'
  } else if (allBinaryArray[10] == 1) {
    callPhone = true
    code = 'E4'
    title = '长时间补水'
  } else if (allBinaryArray[11] == 1) {
    callPhone = true
    code = 'E5'
    title = '进水温度检测异常'
  } else if (allBinaryArray[12] == 1) {
    callPhone = true
    code = 'E6'
    title = '出水温度检测异常'
  } else if (allBinaryArray[13] == 1) {
    callPhone = true
    code = 'E7'
    title = '通讯异常'
  } else if (allBinaryArray[14] == 1) {
    callPhone = true
    code = 'E9'
    title = '漏水保护'
  } else if (allBinaryArray[15] == 1) {
    callPhone = true
    code = 'E10'
    title = '进水管路漏水'
  } else if (allBinaryArray[16] == 1) {
    callPhone = true
    code = 'E12'
    title = '水箱缺水'
  } else if (allBinaryArray[18] == 1) {
    callPhone = true
    code = 'E8'
    title = '低温保护'
  } else if (allBinaryArray[19] == 1) {
    callPhone = true
    code = 'E13'
    title = '流量计故障'
  } else if (allBinaryArray[20] == 1) {
    callPhone = true
    code = 'E14'
    title = 'TDS故障'
  } else if (allBinaryArray[21] == 1) {
    callPhone = true
    code = 'E3'
    title = '干烧报警'
  } else if (allBinaryArray[22] == 1) {
    callPhone = true
    code = 'E11'
    title = '水箱溢水'
  } else if (allBinaryArray[25] == 1) {
    generalTips = true
    notice.description = '进水管路停水，请耐心等待供水恢复'
  } else if (allBinaryArray[31] == 1) {
    generalTips = true
    notice.description = '水箱补水中，请您耐心等待'
  }
  if (callPhone) {
    let description = `（${code}）${title}`
    notice.description = description
    notice.action = {
      type: ActionType.InvokeMethod,
      title,
      linkText: '查看如何解决',
      method: 'showErrorModal',
    }
  }
  if (callPhone || generalTips) {
    errorTitle.value = title
    errorCode.value = code
    store.addNotice(notice)
  } else {
    hideErrorContact()
    errorTitle.value = ''
    errorCode.value = ''
    store.removeNotice(notice)
  }
}

function handleValueErrorCode(value: number) {
  let notice: Notice = {
    key: BIWD_WATERTREATMENT_ERRORCODE,
    value,
    description: '',
    closable: false,
    color: 2,
    ranking: 1,
    brand: store._datasource.brand,
    type: store._datasource.type,
    vib: store._datasource.vib,
    action: null,
  }
  let code = ''
  let title = ''
  if (value === 1) {
    code = 'E1'
    title = '加热部件故障（加热体不加热)出超过85℃以上'
  } else if (value === 2) {
    code = 'E2'
    title = '制水异常(连续检测高压开关制水30分钟）'
  } else if (value === 3) {
    code = 'E3'
    title = '干烧报警(加热体干烧报警）'
  } else if (value === 4) {
    code = 'E4'
    title = '热水补水异常（热水供水箱非出水状态下连续补水5分钟）'
  } else if (value === 5) {
    code = 'E5'
    title = '热水进水NTC故障(加热体检测不到进水温度）'
  } else if (value === 6) {
    code = 'E6'
    title = '热水出水NTC故障(加热体检测不到出水温度）'
  } else if (value === 7) {
    code = 'E7'
    title = '主控板和加热体'
  } else if (value === 8) {
    code = 'E8'
    title = '低温报警(进水温度低于5度）'
  } else if (value === 9) {
    code = 'E9'
    title = '漏水保护（漏报检测到漏水）'
  } else if (value === 11) {
    code = 'E11'
    title = '水箱溢水（水箱检测到溢水位）'
  } else if (value === 12) {
    code = 'E12'
    title = '热水缺水（加热体水泵空抽)'
  } else if (value === 13) {
    code = 'E13'
    title = '流量计故障（出水状态3分钟检测不到脉冲信号）'
  } else if (value === 14) {
    code = 'E14'
    title = 'TDS异常（检测不到TDS)'
  } else if (value === 15) {
    code = 'E15'
    title = '通讯异常-显示板和wifi模块'
  } else if (value === 16) {
    code = 'E16'
    title = '主控板和显示板'
  } else if (value === 17) {
    code = 'E17'
    title = '冷水补水异常（冷水箱非出水状态下连续补水5分钟）'
  } else if (value === 18) {
    code = 'E18'
    title = '制冷异常（非出水状态下连续制冷1h，仍未停止制冷）'
  } else if (value === 19) {
    code = 'E19'
    title = '冷水NTC异常（检测不到冷水NTC或冷水NTC检测值不在-10℃-50℃以内）两个NTC均损坏'
  } else if (value === 21) {
    code = 'E21'
    title = '水质异常'
  }
  let description = `（${code}）${title}`
  notice.description = description
  notice.action = {
    type: ActionType.InvokeMethod,
    linkText: '查看如何解决',
    title,
    method: 'showErrorModal',
  }
  if (value !== 0) {
    errorTitle.value = title
    errorCode.value = code
    store.addNotice(notice)
  } else {
    hideErrorContact()
    errorTitle.value = ''
    errorCode.value = ''
    store.removeNotice(notice)
  }
}

/**
 * 通知栏操作
 */
const noticeExternalMethods = {
  showErrorModal,
}
function showErrorModal() {
  errorVisible.value = true
}
const phoneVisible = ref(false)
function showServePhone() {
  phoneVisible.value = true
  errorVisible.value = false
}
function hideErrorContact() {
  phoneVisible.value = false
  errorVisible.value = false
}
function callPhone() {
  uni.makePhoneCall({
    phoneNumber: phoneNumber.value,
  })
}
</script>
<style lang="less">
.biwd {
  .notify-text {
    text-align: center;
  }
  .error-code {
    font-size: 24rpx;
    font-weight: 400;
    color: var(--dark-color);
  }
  .error-des {
    font-family: PingFang SC;
    font-size: 32rpx;
    font-style: normal;
    font-weight: 400;
    line-height: 46rpx;
    color: var(--dark-color);
    text-align: left;
    margin: 70rpx 0 66rpx;
  }
  .phone-box {
    display: flex;
    justify-content: space-between;
    align-items: flex-end;
    padding-left: 6rpx;
    .error-phone-box {
      .phone-title {
        font-size: 28rpx;
        font-weight: 400;
        color: var(--dark-color);
        text-align: left;
      }
      .phone {
        font-size: 40rpx;
        font-weight: 500;
        color: var(--primary-color);
      }
    }
    .call-phone {
      display: flex;
      align-items: center;
      text {
        font-size: 28rpx;
        font-weight: 400;
        color: var(--dark-color);
        text-decoration: underline;
        margin-right: 8rpx;
      }
      .call-right-arrow {
        width: 28rpx;
        height: 28rpx;
      }
    }
  }
}
</style>
